from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.views.generic.detail import DetailView
from django.contrib.auth import logout
from ittctalk.models import IttcTalk

class DashboardView(DetailView):
    model = IttcTalk
    template_name = "accounts/dashboard.html"
    def get_object(self):
        try:
            obj = IttcTalk.objects.latest("pk")
        except IttcTalk.DoesNotExist:
            obj = None
        return obj

def dologout(request):
    logout(request)
    return HttpResponseRedirect("/accounts/dashboard/")

def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = auth.authenticate(username = username, password = password )
        if user is not None:
            auth.login(request, user)
            # Check if we need to redirect user after login
            next_url = request.GET.get("next")
            if next_url != None:
                return HttpResponseRedirect(next_url)
            return HttpResponseRedirect("/accounts/dashboard/")
    return render_to_response("registration/login.html", context_instance=RequestContext(request))

@login_required
def changepassword(request):
    return render_to_response("accounts/changepassword.html")

@login_required
def profile(request):
    return render_to_response("accounts/profile.html")

def denied(request):
    next_url = request.GET.get("next")
    
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login/?next=%s" % next_url)
    
    return render_to_response(
                "accounts/denied.html"
                , {
                   "next": next_url
                })
